//
//  StatzPlugin.m
//  Statz
//
//  Created by dmaclach on 6/20/07.
//
// Copyright 2007 Google Inc.
// 
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations under
// the License.
//

#import "StatzPlugin.h"


@implementation StatzPlugin

- (id)initWithNibNamed:(NSString*)nibName {
  if ((self = [super init])) {
    nib = [[NSNib alloc] initWithNibNamed:nibName
                                   bundle:[NSBundle bundleForClass:[self class]]];
    if (!nib) {
      [self release];
      self = nil;
    }
  }
  return self;
}
      
- (void)dealloc {
  [nib release];  
  [super dealloc];
}

- (NSString*)appBundleID {
  return nil;
}


- (NSString*)serverName {
  return nil;
}

- (NSString*)uuid {
  return nil;
}

- (NSImage *)image {
  NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
  NSString *path = [workspace absolutePathForAppBundleWithIdentifier:[self appBundleID]];
  if (path) {
    NSImage *icon = [workspace iconForFile:path];   
    if (icon) return icon;
  }
  return [NSImage imageNamed:@"Statz"];
}


- (NSComparisonResult)compareName:(id)otherPlugin {
  return [[self name] compare:[otherPlugin name] options:NSCaseInsensitiveSearch];
}

- (void)updateStatusThread:(StatusUpdate*)sender {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  StatzUpdateValue value = [self updateStatz:sender];
  switch (value) {
    case kStatzUpdateSuccess:
      [[NSApp delegate] performSelectorOnMainThread:@selector(statusUpdatedForSink:) 
                                         withObject:self 
                                      waitUntilDone:NO];
      break;
    
    case kStatzUpdateError:
      NSLog(@"Update Error for %@ -> %@", self, sender);
      break;
      
    default:
      break;
  }
  [pool release];
}

- (StatzUpdateValue)updateStatz:(StatusUpdate*)sender {
  return kStatzUpdateError;
}

- (NSWindow*)preferencesWindow {
  if (nib && !preferencesWindow) {
    NSArray *topObjects;
    [nib instantiateNibWithOwner:self topLevelObjects:&topObjects];
  }
  return preferencesWindow;
}

- (void)showAccountPreferences:(id)sender {
  NSWindow *prefWindow = [self preferencesWindow];
  if (prefWindow) {
    NSWindow *master = [NSApp keyWindow];
    [NSApp beginSheet:prefWindow modalForWindow:master 
        modalDelegate:self didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
          contextInfo:self];
    [NSApp activateIgnoringOtherApps:YES];
  } else {
    NSBeep();
  }
}

- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
  if (returnCode == 1) {
    [self savePreferences];
  } else {
    [self cancelPreferences];
  }
  [sheet orderOut:self];
}

- (BOOL)hasPreferences {
  return NO;
}

- (IBAction)closePreferences:(id)sender {
  int tag = [sender tag];
  if (tag != 1  || (tag == 1 && [self shouldPreferencesClose])) {
    [NSApp endSheet:[self preferencesWindow] returnCode:[sender tag]];
  } else {
    NSBeep();
  }
}

- (BOOL)shouldPreferencesClose {
  [NSApp activateIgnoringOtherApps:YES];
  return [preferencesWindow makeFirstResponder:nil];
}

- (void)savePreferences {
  [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)cancelPreferences {
}

- (NSString*)fullPrefNameForPreferences:(NSString*)preference {
  NSString *prefix = [self appBundleID];
  if (!prefix) {
    prefix = [self serverName];
  }
  return [prefix stringByAppendingFormat:@".%@", preference];
}

- (BOOL)appHasStatusMenuItem {
  return NO;
}

- (NSString*)name {
  NSString *bundleID = [self appBundleID];
  NSString *name = nil;
  if (bundleID) {
    NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
    NSString *path = [workspace absolutePathForAppBundleWithIdentifier:bundleID];
    if (path) {
      NSBundle *bundle = [NSBundle bundleWithPath:path];
      name = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
      if (!name) {
        name = [bundle objectForInfoDictionaryKey:@"CFBundleName"];
        if (!name) {
          name = [bundle objectForInfoDictionaryKey:@"CFBundleExecutable"];
        }
      }
    }    
  }
  if (!name) {
    name = @"StatzPlugin!";
  }
  return name;
}

// Don't cause errors for undefined key value accesses
- (id)valueForUndefinedKey:(NSString *)key {
  NSLog(@"%@ does not define key %@", self, key);
  return nil; 
}
// Given that an invocation of -setValue:forKey: would be unable to set the keyed value using its default mechanism, set the keyed value using some other mechanism. The default implementation of this method raises an NSUndefinedKeyException.
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
  NSLog(@"%@ cannot set key %@", self, key);
}

- (NSString*)username {
  return nil;
}

- (NSString*)password {
  return nil;
}

- (Status*)currentStatus { 
  return nil;
}

- (unsigned int)stateMenuMask { 
  return kStatzStateNone;
}

@end
